#include "junix.h"
#define  A_LONG_TIME 10000

int sockt;


int talk()
{
        fd_set read_template, read_set;
        int stdin_fd = fileno (stdin);
        int len, num_fds;
        char buf[BUFSIZ];
        struct timeval wait;

        fprintf(stdout,"Connection established\n");
       
        FD_ZERO (&read_template);
        FD_SET (sockt, &read_template);
        FD_SET (stdin_fd, &read_template);
        num_fds = (stdin_fd > sockt ? stdin_fd : sockt) + 1;

        for (;;)
        {
                read_set = read_template;
                wait.tv_sec = A_LONG_TIME;
                wait.tv_usec = 0;
                len = select (num_fds, &read_set, 0, 0, &wait);
                if (len <= 0)
                {
                        if (errno == EINTR)
                        {
                                read_set = read_template;
                                continue;
                        }

                        err_quit("Unexpected error from select");
                }

                if (FD_ISSET (sockt, &read_set))
                {
                      if( (len=Read(sockt, buf, BUFSIZ)) > 0)
                                Write(STDOUT_FILENO, buf, len);
                }

                if (FD_ISSET (stdin_fd, &read_set))
                {
                        if( (len=Read(stdin_fd,buf,BUFSIZ))>0)
                                Write(sockt, buf, len);
                }
        }
}


int main(int argc, char **argv)
{
        sockt=connect_tcp("localhost", "123");
        talk();
    
        exit(0);
}

